import * as vscode from 'vscode';
import { v4 as uuidv4 } from "uuid";

export class VsCodeWebviewProtocol {
    _webview?: vscode.Webview;

    constructor(webview?: vscode.Webview) {
        this._webview = webview;
    }

    get webview() {
        return this._webview;
    }

    send(messageType: string, data: any, messageId?: string): string {
        const id = messageId ?? uuidv4();
        this.webview?.postMessage({
          messageType,
          data,
          messageId: id,
        });
        return id;
      }

    /**
     * 向webview发送请求，并获得返回结果
     * 
     * 使用方法：
     * 1：不需要返回结果
     * webviewProtocol?.request("highlightedCode", {
     *         rangeInFileWithContents,
     * });
     * 
     * 2：需要返回结果
     * const isInputFocused = await webviewProtocol.request(
     *     "isFocused",
     *     undefined,
     *     false,
     * );
     * 
     * @param messageType 
     * @param data 
     * @returns 
     */
    public request(messageType: string, data: any): Promise<any> {
        const messageId = uuidv4();

        return new Promise((resolve) => {
            this.send(messageType, data, messageId);

            if (this.webview) {
                // 这种监听器只用一次，用完立即销毁
                const disposable = this.webview.onDidReceiveMessage(
                  (msg: any) => {
                    if (msg.messageId === messageId) {
                      resolve(msg.data);
                      disposable?.dispose();
                    }
                  },
                );
            } else {
                resolve(undefined);
            }
        })
    }
}
